package com.plugin.wukong;

import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.ganide.utils.LogHelp.LogHelp;
import com.ganide.utils.WifiConnect;
import com.ganide.wukit.clibinterface.ClibLedInfo;
import com.ganide.wukit.kitapis.KitConfigApi;
import com.ganide.wukit.kits.BaseKit;
import com.ganide.wukit.kits.WukitEventHandler;
import com.ganide.wukit.kits.clibevent.BaseEventMapper;
import com.ganide.wukit.support_devs.airctrl.AirplugKit;
import com.ganide.wukit.support_devs.eh_wk.EhAirplugKit;
import com.ganide.wukit.user.KitLanDev;

import com.ganide.wukit.clibinterface.ClibAirPlugInfo;
import com.ganide.wukit.support_devs.eh_wk.EhAirplugKit;
import com.plugin.wukong.SdkDemoApplication;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * This class echoes a string called from JavaScript.
 */
public class WukongPlugin extends CordovaPlugin implements WukitEventHandler {
    AirplugKit acKit;
    private static int mHandle;
    CallbackContext devCallback;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("coolMethod")) {
            String message = args.getString(0);
            this.coolMethod(message, callbackContext);
            return true;
        }
        if (action.equals("initConfig")) {
            this.initConfig(callbackContext);
            return true;
        }
        if (action.equals("smartConfig")) {
            String ssid = args.getString(0);
            String pwd = args.getString(1);
            this.smartConfig(ssid, pwd, callbackContext);
            return true;
        }
        if (action.equals("addDev")) {
            String sn = args.getString(0);
            this.addDev(sn, callbackContext);
            devCallback = callbackContext;
            return true;
        }
        if (action.equals("cloudMatch")) {
            mHandle = args.getInt(0);
            this.cloudMatch(callbackContext);
//            this.addTemp(callbackContext);
            return true;
        }
        if (action.equals("changePower")) {
            mHandle = args.getInt(0);
            this.changePower(callbackContext);
            return true;
        }
        if (action.equals("changeTemp")) {
            mHandle = args.getInt(0);
            int add = args.getInt(1);
            this.changeTemp(add, callbackContext);
            return true;
        }
        if (action.equals("changeUpdown")) {
            mHandle = args.getInt(0);
            this.changeUpdown(callbackContext);
            return true;
        }
        if (action.equals("changeMode")) {
            mHandle = args.getInt(0);
            this.changeMode(callbackContext);
            return true;
        }
        if (action.equals("changeSpeed")) {
            mHandle = args.getInt(0);
            this.changeSpeed(callbackContext);
            return true;
        }
        return false;
    }

    public void changeSpeed(CallbackContext callbackContext) {
        ClibAirPlugInfo info = acKit.acGetInfo(mHandle);
        if (info != null) {
            byte windPower = info.air_work_stat.wind;
            ++windPower;
            if (windPower > ClibAirPlugInfo.WIND_LOW) {
                windPower = ClibAirPlugInfo.WIND_AUTO;
            }
            acKit.acSetWindGear(mHandle, windPower);
        }
        callbackContext.success();
    }

    public void changeMode(CallbackContext callbackContext) {
        ClibAirPlugInfo info = acKit.acGetInfo(mHandle);
        if (info != null) {
            byte mode = info.air_work_stat.mode;
            ++mode;
            if (mode > ClibAirPlugInfo.MODE_HOT) {
                mode = ClibAirPlugInfo.MODE_AUTO;
            }
            acKit.acSetMode(mHandle, mode);
        }
        callbackContext.success();
    }

    private void changePower(CallbackContext callbackContext){
        ClibAirPlugInfo info = acKit.acGetInfo(mHandle);
        if (info != null) {
            acKit.acSetPower(mHandle, !info.air_work_stat.onoff);
        }
        callbackContext.success();
    }

    private void addDev(String sn, CallbackContext callbackContext){
        SdkDemoApplication.getKit().addDev(sn, "123456");

        ArrayList<Integer> handles = SdkDemoApplication.getKit().getAllDevHandles();
        for(int i=0; i<handles.size(); i++){
            if (SdkDemoApplication.getKit().getSn(handles.get(i)) == Long.valueOf(sn)){
                SdkDemoApplication.getKit().registerEvent(BaseEventMapper.UE_BEGIN, BaseEventMapper.UE_END, handles.get(i), this);
                SdkDemoApplication.getKit().registerEvent(BaseEventMapper.CE_BEGIN, BaseEventMapper.CE_END, handles.get(i), this);
                SdkDemoApplication.getKit().registerEvent(BaseEventMapper.SAE_BEGIN, BaseEventMapper.SAE_END, handles.get(i), this);

                acKit = (AirplugKit)SdkDemoApplication.getKit();
                mHandle = handles.get(i);
                callbackContext.success("" + handles.get(i), true);
            }
        }
        callbackContext.error("not found device", true);
    }



    public void changeUpdown(CallbackContext callbackContext) {
        ClibAirPlugInfo info = acKit.acGetInfo(mHandle);
        if (info != null) {
            byte derect = info.air_work_stat.wind_direct;
            ++derect;
            if (derect > ClibAirPlugInfo.WIND_DIR_3) {
                derect = ClibAirPlugInfo.WIND_DIR_AUTO;
            }
            acKit.acSetWindDirection(mHandle, derect);
        }
        callbackContext.success();
    }

    private void changeTemp(int add, CallbackContext callbackContext) {

        ClibAirPlugInfo info = acKit.acGetInfo(mHandle);
        if (info != null) {
            if(add > 0){
                for(int i=0; i<add; i++){
                    acKit.acSetTemp(mHandle, ++info.air_work_stat.temp);
                }
            } else {
                for(int i=0; i>add; i--){
                    acKit.acSetTemp(mHandle, --info.air_work_stat.temp);
                }
            }
        }
        callbackContext.success();
    }

    private void coolMethod(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) {
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }

    public CallbackContext smartCallback;
    private void smartConfig(String ssid, String pwd, CallbackContext callbackContext) {
        if (ssid != null && ssid.length() > 0) {
            smartCallback = callbackContext;
            Toast.makeText(this.cordova.getContext(), "开始搜索", Toast.LENGTH_LONG).show();
            SdkDemoApplication.getKit().startSmartConfig(ssid, pwd, KitConfigApi.CONF_MODE_MUT, 60);
        } else {
            callbackContext.error("SSID不能为空");
        }
    }

    public CallbackContext cloudCallback;

    private void cloudMatch(CallbackContext callbackContext) {
//        if (sdk instanceof AirplugKit) {
//            acKit = (AirplugKit) sdk;
//        }
//        cloudCallback = callbackContext;
//        sdk.registerEvent(BaseEventMapper.SAE_BEGIN, BaseEventMapper.SAE_END, handle, this);
//
//        acKit.acStartCodeMatch(handle, 120);
//        ArrayList<KitLanDev> lanDevs = SdkDemoApplication.getKit().getLanDevInfo();
//        KitLanDev kitLanDev = null;
//        if (lanDevs != null && lanDevs.size() > 0) {
//            kitLanDev = lanDevs.get(0);
//        }
//        SdkDemoApplication.getKit().addDev(String.valueOf(kitLanDev.dev_sn), "123456");


//        int testHandle = 0;
//        ArrayList<Integer> handles = SdkDemoApplication.getKit().getAllDevHandles();
//        if (handles != null && handles.size() > 0) {
//            testHandle = handles.get(0);
//        }

        Toast.makeText(this.cordova.getContext(), "" + mHandle, Toast.LENGTH_SHORT).show();

        Intent it = new Intent();
        it.putExtra("handle", mHandle);
        it.setClass(this.cordova.getContext(), com.plugin.wukong.CloudMatchActivity.class);
        this.cordova.getContext().startActivity(it);
    }


    @Override
    public void onStart() {
        super.onStart();

        SdkDemoApplication.getKit().registerEvent(BaseEventMapper.SC_BEGIN, BaseEventMapper.SC_END,
                WukitEventHandler.HANDLE_ALL, this);

    }


    @Override
    public void onStop() {
        super.onStop();
        SdkDemoApplication.getKit().unRegisterEvent(this);
    }


    public void initConfig(CallbackContext callbackContext) {
        SdkDemoApplication.getKit().registerEvent(BaseEventMapper.SC_BEGIN, BaseEventMapper.SC_END,
                WukitEventHandler.HANDLE_ALL, this);


        callbackContext.success("初始化成功");
        Toast.makeText(this.cordova.getContext(), "初始化成功", Toast.LENGTH_LONG).show();
    }



    private void refreshDesc() {
        ClibAirPlugInfo info = acKit.acGetInfo(mHandle);
        ClibLedInfo ledInfo = acKit.ledGetInfo(mHandle);
        if (info != null && ledInfo != null) {
//            String descStr = String.format("开关:%s 模式:%s 温度:%d 风速:%s 风向:%s led灯:%s",
//                    powerDesc(info.air_work_stat.onoff),
//                    modeDesc(info.air_work_stat.mode),
//                    info.air_work_stat.temp,
//                    windPowerDesc(info.air_work_stat.wind),
//                    windDirectDesc(info.air_work_stat.wind_direct),
//                    ledDesc(ledInfo));
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.
            String status = "" + info.air_work_stat.onoff + "##" + info.air_work_stat.mode
                    + "##" + info.air_work_stat.temp
                    + "##" + info.air_work_stat.wind
                    + "##" + info.air_work_stat.wind_direct
                    + "##" + ledInfo.led_mod
                    + "##" + info.room_temp;
            if(devCallback !=null) {
                devCallback.success(status, true);
            }
        }
    }

    public void callback(int skdEvent, int obj_handle, int err_no) {
        switch (skdEvent) {
            case BaseEventMapper.SC_CONFIG_OK:
                ArrayList<KitLanDev> lanDevs = SdkDemoApplication.getKit().getLanDevInfo();
                if (lanDevs != null) {
                    boolean found = false;
                    for (KitLanDev lanDev : lanDevs) {
                        if (lanDev.handle == obj_handle) {

                            smartCallback.success(String.valueOf(lanDev.dev_sn));
                            Toast.makeText(this.cordova.getContext(), String.valueOf(lanDev.dev_sn) + " 配置成功", Toast.LENGTH_LONG).show();
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        smartCallback.error("配置成功，但是没找到设备");
                        Toast.makeText(this.cordova.getContext(), "配置成功，但是没找到设备", Toast.LENGTH_LONG).show();
                    }
                }
                break;
            case BaseEventMapper.CE_CTRL_OK:
                Toast.makeText(this.cordova.getContext(), "控制成功", Toast.LENGTH_SHORT).show();
                break;
            case BaseEventMapper.CE_CTRL_FAIL:
                Toast.makeText(this.cordova.getContext(), "控制失败", Toast.LENGTH_SHORT).show();
                break;
            case BaseEventMapper.UE_MODIFY:
                refreshDesc();
                break;
            case BaseEventMapper.SC_CONFIG_FAIL:
                smartCallback.error("配置失败");
                Toast.makeText(this.cordova.getContext(), "配置失败", Toast.LENGTH_LONG).show();
                break;
            case BaseEventMapper.SAE_CODE_MATCH_READY:
                LogHelp.logDebug("ready\n");
                cloudCallback.success("ready");
                break;
            case BaseEventMapper.SAE_CODE_MATCH_PROCESS:
                LogHelp.logDebug("xxxddd percent " + err_no);
                cloudCallback.success(err_no);
                break;
            case BaseEventMapper.SAE_CODE_MATCH_OK:
                ClibAirPlugInfo info = acKit.acGetInfo(mHandle);
                LogHelp.logDebug("code match success\n");
                cloudCallback.success("code match success");
                break;
            case BaseEventMapper.SAE_CODE_MATCH_FAILED:
                LogHelp.logDebug("fail\n");
                cloudCallback.error("fail");
                break;
            default:
                break;
        }
    }
}
